﻿using System;
using System.IO;
using System.ServiceProcess;
using System.Threading.Tasks;

namespace AntiVirus_Project
{
    class ClamAVMonitor
    {
        private FileSystemWatcher _fileWatcher;
        private readonly string _filePath;
        private readonly TimeSpan _delayBeforeRestart = TimeSpan.FromMinutes(1);

        public ClamAVMonitor(string filePath)
        {
            _filePath = filePath ?? throw new ArgumentNullException(nameof(filePath));
        }

        public void StartMonitoring()
        {
            // 创建并初始化文件系统监控器
            _fileWatcher = new FileSystemWatcher(Path.GetDirectoryName(_filePath), Path.GetFileName(_filePath));
            _fileWatcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size; // 监听写入和大小变化
            _fileWatcher.Changed += OnFileChanged;
            _fileWatcher.EnableRaisingEvents = true;
        }

        private async void OnFileChanged(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine($"freshclam.dat 文件已发生变化，将在 {_delayBeforeRestart.TotalSeconds} 秒后重启 clamd 服务...");

            // 使用延迟任务重启服务
            await Task.Delay(_delayBeforeRestart);

            // 检查并安全重启 clamd 服务
            using (var serviceController = new ServiceController("clamd"))
            {
                if (serviceController.Status != ServiceControllerStatus.Stopped)
                {
                    Console.WriteLine("正在停止 clamd 服务...");
                    serviceController.Stop();
                    serviceController.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(30)); // 等待服务停止

                    if (serviceController.Status == ServiceControllerStatus.Stopped)
                    {
                        Console.WriteLine("clamd 服务已停止，现在开始重启...");
                        serviceController.Start();
                        serviceController.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(30)); // 等待服务启动
                        Console.WriteLine("clamd 服务已成功重启.");
                    }
                    else
                    {
                        Console.WriteLine("未能成功停止 clamd 服务以进行重启.");
                    }
                }
                else
                {
                    Console.WriteLine("clamd 服务未运行，无需重启.");
                }
            }
        }

        public void StopMonitoring()
        {
            if (_fileWatcher != null)
            {
                _fileWatcher.EnableRaisingEvents = false;
                _fileWatcher.Dispose();
            }
        }
    }
}